package com.selfdriving.activity;

import java.util.ArrayList;
import java.util.List;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.selfdriving.BaseFragmentActivity;
import com.selfdriving.R;
import com.selfdriving.dialog.ChooseDialog;
import com.selfdriving.dialog.MessageDialog;
import com.selfdriving.utils.Constant;
import com.selfdriving.utils.DeviceUtils;
import com.selfdriving.utils.Utils;
import com.selfdriving.utils.ViewFlipperView;
import com.selfdriving.wl.activity.ActivityNotice;
import com.selfdriving.wl.activity.BestFeaturePoplular;
import com.selfdriving.wl.activity.FeatureJoin;

public class HomeActivity extends BaseFragmentActivity implements
		OnClickListener
{

	private List<View> listViewsOne; // Tab页面列表
	private ViewPager mPager;// 页卡内容
	private ImageView cursor;// 动画图片
	private Button btn1, btn2, btn3;// 页卡头标
	private int offset = 0;// 动画图片偏移量
	private int currIndex = 0;// 当前页卡编号
	private int bmpW;// 动画图片宽度
	private MyPagerAdapter adapterOne;
	/** View1 **/
	private ActivityNotice activityNotice;
	/** View3 **/
	private FeatureJoin featureJoin;
	/** View2 **/
	private BestFeaturePoplular bestFeaturePoplular;
	// private BestFeatureSoaring bestFeatureSoaring;
	private MessageDialog phoneDialog;
	private MessageDialog mailDialog;
	private int flag = 0;
	private TextView title;
	ChooseDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.w_activity_home_page);
		Utils.checkLoading(mApplication, this);
		initViews();
		initEvents();
		InitImageView();
		InitViewPager();
	}

	@Override
	protected void onResume()
	{
		// TODO Auto-generated method stub
		super.onResume();
		getOnLineUser();
		activityNotice.getRunText();
	}

	@Override
	protected void initViews()
	{
		btn1 = (Button) findViewById(R.id.home_but1);
		btn2 = (Button) findViewById(R.id.home_but2);
		btn3 = (Button) findViewById(R.id.home_but3);
		title = (TextView) findViewById(R.id.top_text);
	}

	@Override
	protected void initEvents()
	{
		btn1.setOnClickListener(new MyOnClickListener(0));
		btn2.setOnClickListener(new MyOnClickListener(1));
		btn3.setOnClickListener(new MyOnClickListener(2));
	}

	/** 初始化动画 **/
	private void InitImageView()
	{
		cursor = (ImageView) findViewById(R.id.cursor);
		offset = (mScreenWidth / 3 - bmpW) / 2;// 计算偏移量
		Matrix matrix = new Matrix();
		matrix.postTranslate(offset, 0);
		cursor.setImageMatrix(matrix);// 设置动画初始位置
	}

	/** 初始化ViewPager **/
	private void InitViewPager()
	{
		mPager = (ViewPager) findViewById(R.id.vPager);
		listViewsOne = new ArrayList<View>();
		activityNotice = new ActivityNotice(mApplication, this);
		featureJoin = new FeatureJoin(mApplication, this, this);
		bestFeaturePoplular = new BestFeaturePoplular(mApplication, this);
		listViewsOne.add(activityNotice.getView());
		listViewsOne.add(bestFeaturePoplular.getView());
		listViewsOne.add(featureJoin.getView());
		adapterOne = new MyPagerAdapter(listViewsOne);
		mPager.setAdapter(adapterOne);
		mPager.setOnPageChangeListener(new MyOnPageChangeListener());
		mPager.setCurrentItem(0);
		getHomeVFData(activityNotice.getViewFlipperRL(),
				activityNotice.getViewText(), activityNotice.getLradio());
	}

	Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			switch (msg.what)
			{
			case 1:
				getHomeVFData(activityNotice.getViewFlipperRL(),
						activityNotice.getViewText(),
						activityNotice.getLradio());
				break;
			}
		}
	};

	private void getHomeVFData(final LinearLayout viewFlipperRL,
			final TextView textView, final LinearLayout Lradio)
	{
		AjaxParams params = new AjaxParams();
		params.put("f", "73");
		FinalHttp fh = new FinalHttp();
		fh.configTimeout(10000);
		fh.post(Constant.POST, params, new AjaxCallBack<Object>()
		{
			@Override
			public void onFailure(Throwable t, String strMsg)
			{
				handler.sendEmptyMessageAtTime(1, 1000);
			}

			@Override
			public void onSuccess(Object o)
			{
				String json = o.toString();
				try
				{
					JSONArray array = new JSONArray(json);
					String imgs[] = new String[array.length()];
					for (int i = 0; i < array.length(); i++)
					{
						JSONObject object = array.getJSONObject(i);
						String id = object.getString("id");
						String title = object.getString("title");
						String img = object.getString("img");
						imgs[i] = img;
					}
					if (viewFlipperRL.getChildCount() > 0)
					{
						viewFlipperRL.removeAllViews();
					}
					ViewFlipperView flipperView = new ViewFlipperView(
							mApplication, HomeActivity.this, textView, Lradio,
							0, imgs);
					viewFlipperRL
							.addView(flipperView.viewFlipper, layoutParams);
				} catch (JSONException e)
				{
					handler.sendEmptyMessageAtTime(1, 1000);
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * ViewPager适配器
	 */
	public class MyPagerAdapter extends PagerAdapter
	{
		public List<View> mListViews;
		public int mCount;

		public MyPagerAdapter(List<View> mListViews)
		{
			this.mListViews = mListViews;
			mCount = mListViews.size();
		}

		@Override
		public void destroyItem(View collection, int position, Object arg2)
		{
			((ViewPager) collection).removeView(mListViews.get(position));
			if (position >= mListViews.size())
			{
				int newPosition = position % mListViews.size();
				position = newPosition;
			}
			if (position < 0)
			{
				position = -position;
			}
		}

		public void finishUpdate(View arg0)
		{
		}

		public int getCount()
		{
			// return mListViews.size();
			return mCount;// 更改实现无限循环
		}

		public Object instantiateItem(View collection, int position)
		{
			try
			{
				((ViewPager) collection).addView(mListViews.get(position), 0);
			} catch (Exception e)
			{
			}
			return mListViews.get(position);
		}

		public boolean isViewFromObject(View arg0, Object arg1)
		{
			return arg0 == arg1;
		}

		public void restoreState(Parcelable arg0, ClassLoader arg1)
		{
		}

		public Parcelable saveState()
		{
			return null;
		}

		public void startUpdate(View arg0)
		{
		}
	}

	/**
	 * 头标点击监听
	 */
	public class MyOnClickListener implements View.OnClickListener
	{
		private int index = 0;

		public MyOnClickListener(int i)
		{
			index = i;
		}

		public void onClick(View v)
		{
			mPager.setCurrentItem(index);
		}
	};

	/**
	 * 页卡切换监听
	 */
	public class MyOnPageChangeListener implements OnPageChangeListener
	{

		int one = offset * 2 + bmpW;// 页卡1 -> 页卡2 偏移量
		int two = one * 2;// 页卡1 -> 页卡3 偏移量

		public void onPageSelected(int arg0)
		{
			Animation animation = null;
			switch (arg0)
			{
			case 0:
				flag = 0;
				btn1.setTextColor(getResources().getColor(R.color.white));
				btn2.setTextColor(getResources().getColor(R.color.title));
				btn3.setTextColor(getResources().getColor(R.color.title));
				if (currIndex == 1)
				{
					animation = new TranslateAnimation(one, 0, 0, 0);
				} else if (currIndex == 2)
				{
					animation = new TranslateAnimation(two, 0, 0, 0);
				}
				break;
			case 1:
				flag = 1;
				btn1.setTextColor(getResources().getColor(R.color.title));
				btn2.setTextColor(getResources().getColor(R.color.white));
				btn3.setTextColor(getResources().getColor(R.color.title));
				if (currIndex == 0)
				{
					animation = new TranslateAnimation(offset, one, 0, 0);
				} else if (currIndex == 2)
				{
					animation = new TranslateAnimation(two, one, 0, 0);
				}
				break;
			case 2:
				flag = 2;
				btn1.setTextColor(getResources().getColor(R.color.title));
				btn2.setTextColor(getResources().getColor(R.color.title));
				btn3.setTextColor(getResources().getColor(R.color.white));
				if (currIndex == 0)
				{
					animation = new TranslateAnimation(offset, two, 0, 0);
				} else if (currIndex == 1)
				{
					animation = new TranslateAnimation(one, two, 0, 0);
				}
				featureJoin.page = 1;
				featureJoin.getDatas(false);
				break;
			}
			currIndex = arg0;
			animation.setFillAfter(true);// True:图片停在动画结束位置
			animation.setDuration(300);
			cursor.startAnimation(animation);
		}

		public void onPageScrolled(int arg0, float arg1, int arg2)
		{
		}

		public void onPageScrollStateChanged(int arg0)
		{
		}
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.ivPhone:
			ivPhone();
			break;
		case R.id.ivMail:
			ivMail();
			break;
		case R.id.dialog_generic_btn_button1:
			if (phoneDialog != null && phoneDialog.isShowing())
			{
				phoneDialog.dismiss();
				DeviceUtils.callPhone(this, "15279107963");
			} else
			{
				mailDialog.dismiss();
				DeviceUtils.sendMail(this, "15279107963");
			}
			break;
		case R.id.dialog_generic_btn_button2:
			if (phoneDialog != null)
			{
				phoneDialog.dismiss();
			}
			if (mailDialog != null)
			{
				mailDialog.dismiss();
			}
		default:
			// dialog=new ChooseDialog(context, st, user)
			break;
		}

	}

	public void ivPhone()
	{
		if (!isLogin())
		{
			Intent intent = new Intent(this, RegisterActivity.class);
			startActivity(intent);
		} else
		{
			phoneDialog = new MessageDialog(this, "提示", "是否要拨打电话", "确定", "取消",
					true, true, this);
			phoneDialog.show();
		}
	}

	public void ivMail()
	{
		if (!isLogin())
		{
			Intent intent = new Intent(this, RegisterActivity.class);
			startActivity(intent);
		} else
		{
			mailDialog = new MessageDialog(this, "提示", "是否要发送邮件", "确定", "取消",
					true, true, this);
			mailDialog.show();
		}
	}

	public void getOnLineUser()
	{
		AjaxParams params = new AjaxParams();
		params.put("f", "15");
		FinalHttp fh = new FinalHttp();
		fh.configTimeout(10000);
		fh.post(Constant.POST, params, new AjaxCallBack<Object>()
		{
			@Override
			public void onFailure(Throwable t, String strMsg)
			{
			}

			@Override
			public void onSuccess(Object o)
			{
				String json = o.toString();
				if (json.contains("result"))
				{
					try
					{
						JSONObject object = new JSONObject(json);
						String numbers = object.getString("result");
						title.setText("当前在线人数：" + numbers);
					} catch (JSONException e)
					{
						e.printStackTrace();
						title.setText("");
					}
				} else
				{
					title.setText("");
				}
			}
		});
	}

}
